//
//  SJUrlArgumentsFilter.m
//  WSL
//
//  Created by CJ on 2017/10/21.
//  Copyright © 2017年 sanjuetech. All rights reserved.
//

#import "SJUrlArgumentsFilter.h"
#import "AFURLRequestSerialization.h"

@implementation SJUrlArgumentsFilter  {
    NSDictionary *_arguments;
}

+ (SJUrlArgumentsFilter *)filterWithArguments:(NSDictionary *)arguments {
    return [[self alloc] initWithArguments:arguments];
}

- (id)initWithArguments:(NSDictionary *)arguments {
    self = [super init];
    if (self) {
        _arguments = arguments;
    }
    return self;
}

- (NSString *)filterUrl:(NSString *)originUrl withRequest:(YTKBaseRequest *)request {
    
    NSMutableDictionary *parameters = [_arguments mutableCopy];
    [request.requestArgument enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        [parameters setObject:obj forKey:key];
    }];
    
    NSMutableDictionary *arguments = [_arguments mutableCopy];
    arguments[@"sign"] = [self createMD5Sign:parameters];
    
    return [self urlStringWithOriginUrlString:originUrl appendParameters:arguments];
}

- (NSString *)urlStringWithOriginUrlString:(NSString *)originUrlString appendParameters:(NSDictionary *)parameters {
    
    NSString *paraUrlString = AFQueryStringFromParameters(parameters);
    
    if (!(paraUrlString.length > 0)) {
        return originUrlString;
    }
    
    BOOL useDummyUrl = NO;
    static NSString *dummyUrl = nil;
    NSURLComponents *components = [NSURLComponents componentsWithString:originUrlString];
    if (!components) {
        useDummyUrl = YES;
        if (!dummyUrl) {
            dummyUrl = @"http://www.sanjuetech.com";
        }
        components = [NSURLComponents componentsWithString:dummyUrl];
    }
    
    NSString *queryString = components.query ?: @"";
    NSString *newQueryString = [queryString stringByAppendingFormat:queryString.length > 0 ? @"&%@" : @"%@", paraUrlString];
    
    components.query = newQueryString;
    
    if (useDummyUrl) {
        return [components.URL.absoluteString substringFromIndex:dummyUrl.length - 1];
    } else {
        return components.URL.absoluteString;
    }
}

- (NSString *)createMD5Sign:(NSDictionary *)dictionary {

    NSMutableString *sign = [NSMutableString string];
    NSArray *allKeys = [dictionary allKeysSorted];
    NSArray *allValues = [dictionary allValuesSortedByKeys];
    for (int i = 0; i < allKeys.count; i++) {
        
        NSString *finalKey = [NSString stringWithFormat:@"%@", allKeys[i]];
        NSString *finalValue = [NSString stringWithFormat:@"%@", allValues[i]];
        NSString *part =[NSString stringWithFormat:@"%@=%@",finalKey, finalValue];
        [sign appendString:part];
    }
    
    [sign appendString:@"key=sanjue@qingluo*2017^meihuaxiangzikuhanlai"];

    return [sign md5String];
    
}

@end
